import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:jaguar/jaguar.dart' hide Interceptor;
import '_mock.dart';
import 'package:dio/dio.dart';

class MockServer {
  static Future<void> startService() async {
    final jaguar = Jaguar(port: BaseConfig.mockPort, multiThread: true);
    jaguar.before.add(_handleBeforeJaguar);
    addRoutes(jaguar);
    ReassembleBroadcast().listener(() async {
      print('reassemble');
      try {
        await jaguar.close();
      } catch (e) {
        print(e);
      }
      addRoutes(jaguar);
      await jaguar.serve(logRequests: true);
    });
    await jaguar.serve(logRequests: true);
  }

  static void addRoutes(Jaguar jaguar) {
    List<Route> routes = [];
    for (final request in mockMap.entries) {
      routes.add(Route.fromInfo(
          HttpMethod(path: request.key, methods: [request.value['method']]),
              (context) => request.value['body']));
    }
    jaguar.add(routes);
  }

  static FutureOr<void> _handleBeforeJaguar(Context ctx) {
    print('mock receive ${ctx.method} ===========> path:${ctx.path}');
  }
}

class MockInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options,
      RequestInterceptorHandler handler,) async {
    if (mockMap.containsKey(options.path) && options.baseUrl != '127.0.0.1') {
      //转到mock请求
      handler.next(
          options..baseUrl = 'http://127.0.0.1:${BaseConfig.mockPort}');
    }
    handler.next(options);
  }
}
